package com.myrock.zlbandy.gorock.rock.ui;


import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.etsy.android.grid.StaggeredGridView;
import com.myrock.zlbandy.gorock.rock.z.MyShare;
import com.myrock.zlbandy.gorock.rock.tools.NetWorkStateReceiver;
import com.myrock.zlbandy.gorock.HttpModel.ParseInfo;
import com.myrock.zlbandy.gorock.rock.tools.ResetItem;
import com.myrock.zlbandy.gorock.HttpModel.Model.RockInfo;
import com.myrock.zlbandy.gorock.R;
import com.myrock.zlbandy.gorock.my.adapter.MyGridViewAdapter;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends BaseActivity implements AbsListView.OnScrollListener,AbsListView.OnItemClickListener,ResetItem{

    private String TAG="MyRock";
    private boolean mHasRequestedMore =false;
    private StaggeredGridView gridView;
    private int page = 1;
    private ArrayList<RockInfo> rockInfoall = new ArrayList<RockInfo>();
    private TextView txtFooterTitle;
    private ProgressBar myProgressBar;
    private TextView textView;
    PopupMenu popupMenu;
    Menu menu;
    private ImageView user;
    private MenuItem login,logout;
    private AlertDialog about;
    private  NetWorkStateReceiver netWorkStateReceiver;
    private boolean isopen=false;



    public static  int[] images = new int[]{
            R.drawable.head1,
            R.drawable.head2,
            R.drawable.head3,
            R.drawable.head4,
            R.drawable.head5,
            R.drawable.head6,
            R.drawable.head7,
            R.drawable.head8,
            R.drawable.head9,
            R.drawable.head10,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        popupMenu = new PopupMenu(this, findViewById(R.id.user));
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popupmenu, menu);
        user = (ImageView)findViewById(R.id.user);
        login = menu.findItem(R.id.login);
        logout = menu.findItem(R.id.logout);

        MyShare myShare = new MyShare(getApplicationContext());
        int i = myShare.Getlogin();
        if(i!=0){
            user.setImageResource(i);
            login.setTitle(myShare.Getname());
            logout.setVisible(true);
        }
        else{
            logout.setVisible(false);
        }

        LayoutInflater layoutInflater = getLayoutInflater();
        View footer = layoutInflater.inflate(R.layout.list_item_header_footer, null);


        textView = (TextView) findViewById(R.id.tv);
        myProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        gridView = (StaggeredGridView) this.findViewById(R.id.grid_view);
        gridView.addFooterView(footer);
        gridView.setOnScrollListener(this);
        gridView.setOnItemClickListener(this);
        txtFooterTitle =  (TextView) footer.findViewById(R.id.txt_title);
        txtFooterTitle.setText("加载中....");

        int margin = 10;
        // set the GridView margin
        gridView.setPadding(margin, 0, margin, 0); // have the margin on the sides as well
        EditText search = (EditText)findViewById(R.id.search_go_btn);
        search.setHintTextColor(Color.parseColor("#787878"));
        search.setFocusable(false);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent  = new Intent(MainActivity.this,MySearch.class);
                startActivity(intent);

            }
        });

        ImageButton classify = (ImageButton)findViewById(R.id.photo);
        classify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyShare myShare = new MyShare(getApplicationContext());
                int i = myShare.Getlogin();
                if(i!=0){
                    Intent intent  = new Intent(MainActivity.this,ClassifyActivity.class);
                    startActivity(intent);
                }else{
                    Toast.makeText(getApplicationContext(),"请先登录",Toast.LENGTH_SHORT).show();
                }

            }
        });

        LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
        View aboutview = inflater.inflate(R.layout.about, null);

        about = new AlertDialog.Builder(MainActivity.this).create();
        about.setView(aboutview);



        Button ok = (Button)aboutview.findViewById(R.id.ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                about.cancel();
            }
        });



        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {



            @Override
            public boolean onMenuItemClick(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.login:
                        Random random=new Random();
                        int i = random.nextInt(10);
                        MyShare myShare = new MyShare(getApplicationContext());
                        myShare.adduser("游客"+String.valueOf(i),images[i]);
                        user.setImageResource(images[i]);
                        login.setTitle("游客"+String.valueOf(i));
                        logout.setVisible(true);
                        break;
                    case R.id.logout:
                        MyShare myShare1 = new MyShare(getApplicationContext());
                        myShare1.clear();
                        user.setImageResource(R.drawable.user);
                        login.setTitle("登录");
                        logout.setVisible(false);
                        break;

                    case R.id.about:
                        about.show();
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

    }

    public void popupmenu(View v) {
        popupMenu.show();
    }
    //在onResume()方法注册
    @Override
    protected void onResume() {
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        netWorkStateReceiver.setResetItem(this);
        System.out.println("注册");
        super.onResume();

    }

    //onPause()方法注销
    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);
        System.out.println("注销");
        super.onPause();
    }


    @Override
    protected void onStart() {
        super.onStart();
        MyShare myShare = new MyShare(getApplicationContext());
        isopen =  myShare.getOpen();
        if(isopen == false){
            about.show();
            myShare.addopen();
        }

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        // our handling
        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                if(page<=10){
                    mHasRequestedMore = true;
                    onLoadMoreItems();
                }else{
                    txtFooterTitle.setTextColor(Color.parseColor("#000000"));
                    txtFooterTitle.setText("图片正在制作中,敬请期待...");
                }
            }
        }
    }

    private void onLoadMoreItems(){
        ImageTask imageTask = new ImageTask(myProgressBar,textView,getApplicationContext());
        imageTask.execute();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent  = new Intent(MainActivity.this,RockInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("rockInfo",rockInfoall.get(position));
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void GetItem() {
        if(page==1){
            onLoadMoreItems();
        }

    }

    //内部类异步加载

    class ImageTask extends AsyncTask<String, Integer, ArrayList<RockInfo>> {

        ProgressBar myprogressbar = null;
        //MainActivity的文本
        TextView textView = null;
        // MainActivity的上下文
        Context mycontext = null;
        //onPreExecute方法用于在执行后台任务前做一些UI操作

        public ImageTask(ProgressBar progressbar, TextView textview, Context context) {
            myprogressbar = progressbar;
            mycontext = context;
            textView = textview;
        }


        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
            myProgressBar.setVisibility(View.VISIBLE);
            textView.setText("正在加载...");
            myprogressbar.setProgress(10);


        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected ArrayList<RockInfo> doInBackground(String... params) {
            ArrayList<RockInfo> arrayList = new ArrayList<RockInfo>();
            arrayList = ParseInfo.GetRock(null,page);
            page++;
            publishProgress(50);
            for(int i = 50;i<99;i++){
                publishProgress(i);
            }

            return arrayList;

        }

        //onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
            int progress = myprogressbar.getMax() / 100 * (progresses[0] + 1);
            myprogressbar.setProgress(progress);
            textView.setText("正在加载..." + progress + "%");

        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(ArrayList<RockInfo> result) {

            myprogressbar.setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
            if(result.size()>0){
                rockInfoall.addAll(result);
                MyGridViewAdapter adapter = new MyGridViewAdapter(MainActivity.this, R.layout.activity_custom_grid_view,
                        rockInfoall, new int[]{R.id.imageView1});
                gridView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                mHasRequestedMore = false;
            }else if(result.size() == 0 && rockInfoall.size()>0){
                txtFooterTitle.setTextColor(Color.parseColor("#000000"));
                txtFooterTitle.setText("图片正在制作中,敬请期待...");
            }else if(rockInfoall.size()==0){
                page = 1;
                Toast.makeText(MainActivity.this," 数据异常,稍等...",Toast.LENGTH_SHORT).show();
            }
        }

        //onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        page = 1;
    }
}
